<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class PaperFeedback extends Model
{
    use SoftDeletes;
    protected $table = 'paper_feedbacks';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];

    public function getSubjectSelectAttribute($subject_select)
    {
        return array_values(json_decode($subject_select, true) ?: []);
    }

    public function setSubjectSelectAttribute($subject_select)
    {
        $this->attributes['subject_select'] = json_encode(array_values($subject_select));
    }

    public function paper_library()
    {
        return $this -> hasOne(PaperLibrary::class,'id','paper_librarie_id');
    }

    // 获取某一张问卷
    public static function getPaper($paper_librarie_id,$region_id = 0)
    {

        $paper_libraries = PaperLibrary::where('id',$paper_librarie_id) -> get(['id','paper_title','paper_remark']) -> first();

        $subject = PaperFeedback::where('paper_librarie_id',$paper_librarie_id);

        if($region_id){
            $subject -> where('region_id',$region_id);
        }
        $res = $subject -> orderBy('subject_no') -> get(['id','subject_no','subject_title','subject_select','region_id','is_multiple']);

        $paper_libraries -> subject = $res;

        return $paper_libraries;
    }

    // 检验答题 是否答完，答案是否为空
    public static function paperCheck($paper_librarie_id,$answer){

        $count  = self::where('paper_librarie_id',$paper_librarie_id) -> count();
        $answer = json_decode($answer,true);
        $num    = count($answer);

        $res = true;
        foreach($answer as $v){
            !$v && $res = false;
        }

        return $count == $num && $res ? true : false;
    }

}
